import Mock, { Random } from "mockjs";

const ls = require("local-storage");
const account = {
  level: "普通账户",
  balance: 5000,
};
const data = Mock.mock({
  "items|20": [
    {
      id: function() {
        return +Random.string("number", 8);
      }, // 商品id
      "title|1": [
        "低价上榜3小时-4号",
        "稳定上榜【2-12小时自选】",
        "4号-占榜赠送粉丝团",
        "6号- 1-24h等级号直播挂榜(送灯牌)",
        "6号-等级号直播挂榜1h+灯牌",
        "s-等级号+粉丝团+点赞3小时",
      ], // 商品标题
      "price|1-20.2-2": 1, // 商品单个的价格
      "cate|1": ["notesOnList", "notesCancelOnList", "notesFans", "notesLike"], // 商品所属的分类
      "orderWay|1": [["视频ID", "DY号"], ["主页链接"], ["作品链接", "备注信息"], ["下单链接"]], // 商品下单方式
      "orderQuantity|1": [1, 10, 50], // 商品默认下单数量
      "detail|1": [
        "<h1>商品说明123</h1><h1>注意事项：撒法帝国感人故沙发沙发事是</h1>",
        "<h1>商品说明456</h1>",
        "<h1>商品说明789</h1><div>注意事项：撒法帝国大幅度反对法</div>",
        "<h1>商品说明147</h1><div>注意事项：撒法帝国感人故事是</div>",
        "<h1>商品说明258</h1><div>注意事项</div>",
        "<h1>商品说明369</h1><div>注意事项：撒法帝国</div>",
      ], // 商品详情
      collected: false, // 商品收藏
    },
  ],
});
// 邀请码
const tempInvitationCode = "123asd";

// 设置拦截ajax请求的相应时间
Mock.setup({
  timeout: "200-600",
});

// 登录接口
Mock.mock("/api/login", "post", (option) => {
  const { username, password } = JSON.parse(option.body);
  const users = ls("users") || [{}];
  if (users.find((v) => v.username == username && v.password == password)) {
    return {
      code: 0,
      message: "登陆成功",
      username,
      qq: ls("qq"),
      token: "sunclass" + "-" + username + "-" + Date.now(),
      loginTime: Date.now(),
      expires: 60 * 60 * 1000, // 有效期为 60 分钟
    };
  } else if (users.find((v) => v.username == username && v.password !== password)) {
    return {
      code: 2,
      message: "账号密码错误",
    };
  } else {
    return {
      code: 1,
      message: "账号不存在",
    };
  }
});

// 注册接口
Mock.mock("/api/register", "post", (option) => {
  const { username, password, qq, invitationCode } = JSON.parse(option.body);
  const users = ls("users") || [{}];
  if (users.find((v) => v.username == username)) {
    return {
      code: 1,
      success: false,
      message: "用户名已存在",
    };
  } else if (users.find((v) => v.username != username && invitationCode != tempInvitationCode)) {
    return {
      code: 2,
      success: false,
      message: "邀请码错误",
    };
  } else if (users.find((v) => v.username != username && invitationCode == tempInvitationCode)) {
    // 用户不存在且邀请码对的时候，添加用户
    users.push({ username, password, qq });
    JSON.stringify(users[0]) === "{}" && users.shift();
    ls("users", users);
    ls("qq", qq);
    return {
      code: 0,
      success: true,
      message: "注册成功",
    };
  }
});

// 获取用户接口
Mock.mock("/api/user", "post", (option) => {
  return {
    code: 200,
    message: "获取用户成功",
    username: ls("username"),
    user: ls("user"),
  };
});

// 修改密码接口
Mock.mock("/api/updatePassword", "put", (option) => {
  const { username, oldPass, newPass } = JSON.parse(option.body);
  const users = ls("users");
  const newUsers = users.map((item) => {
    if (item.username == username && item.password == oldPass) {
      item.password = newPass;
      return item;
    } else {
      return item;
    }
  });
  ls.set("users", newUsers);
  // ls("users", newUsers);
  ls.set("password", newPass);
  return {
    code: 200,
    success: true,
    message: "密码修改成功",
    username: ls("username"),
    users: ls.get("users"),
  };
});

// 获取商品接口
Mock.mock("/api/getGoods", "get", (option) => {
  const goods = data.items;
  return {
    code: 200,
    success: true,
    goods,
  };
});

// 获取商品详情接口
Mock.mock("/api/getGoodsByID", "post", (option) => {
  const { id } = JSON.parse(option.body);
  const item = data.items.find((v) => v.id === id);
  return {
    code: 200,
    success: true,
    item,
  };
});

// 商品收藏接口
Mock.mock("/api/goodsCollect", "post", (option) => {
  const { id } = JSON.parse(option.body);
  const index = data.items.findIndex((item) => item.id === id);
  data.items[index].collected = true;
  const goods = data.items;

  const collectedGoods = ls("collectedGoods") || [];
  collectedGoods.push(data.items[index]);
  ls("collectedGoods", collectedGoods);
  return {
    code: 1,
    success: true,
    message: "收藏成功",
    collectedGoods,
    goods,
  };
});

// 商品取消收藏接口
Mock.mock("/api/goodsCancelCollect", "post", (option) => {
  const { id } = JSON.parse(option.body);
  const index = data.items.findIndex((item) => item.id === id);
  data.items[index].collected = false;
  const goods = data.items;

  const newCollectedGoods = ls("collectedGoods").filter((v) => v.id !== id);
  ls("collectedGoods", newCollectedGoods);
  const collectedGoods = ls("collectedGoods");
  return {
    code: 1,
    success: true,
    message: "取消收藏成功",
    collectedGoods,
    goods,
  };
});

// 获取收藏的商品接口
Mock.mock("/api/getCollectedGoods", "get", (option) => {
  const collectedGoods = ls("collectedGoods") || [];
  return {
    code: 1,
    success: true,
    collectedGoods,
  };
});

// 下单接口
Mock.mock("/api/buy", "post", (option) => {
  const req = JSON.parse(option.body);
  req.orderID = Random.id();
  req.createTime = Random.now();
  const orders = ls("orders") || [];
  orders.unshift(req);
  return {
    success: true,
    message: "下单成功",
    currentOrder: [req],
    orders,
  };
});

// 获取订单列表接口
Mock.mock("/api/getOrders", "get", (option) => {
  const orders = ls("orders") || [];
  return {
    success: true,
    message: "返回成功",
    orders,
  };
});

// 获取账户信息接口
Mock.mock("/api/getAccount", "get", (option) => {
  return {
    success: true,
    message: "返回成功",
    account,
  };
});
// [{"name":"作品链接","value":"第一个输入框的值"},{"name":"备注信息","value":"第二个输入框的值"}]
// 余额明细变动接口
Mock.mock("/api/balanceRecordChange", "post", (option) => {
  const req = JSON.parse(option.body);
  const balanceRecord = ls("balanceRecord") || [];
  const obj = {};
  obj.beforeChange = account.balance;
  account.balance -= req.totalPrice;
  account.balance = Number.parseFloat(account.balance.toFixed(2));
  obj.money = -req.totalPrice;
  obj.surplus = account.balance;
  obj.title = req.title;
  obj.id = +Random.string("number", 8);
  obj.orderDetail = req.orderDetail;
  obj.time = Random.now();
  balanceRecord.unshift(obj);
  ls("balanceRecord", balanceRecord);
  return {
    success: true,
    message: "下单成功",
    balanceRecord,
  };
});

// 获取余额明细接口
Mock.mock("/api/getBalanceRecord", "get", (option) => {
  const balanceRecord = ls("balanceRecord") || [];
  return {
    success: true,
    message: "返回成功",
    balanceRecord,
  };
});

function mock(app) {
  app.post("/api/register", (req, res) => {
    const { username, password } = req.body;
    const users = ls("users") || [];
    if (!users.find((v) => v.username == username)) {
      // 用户不存在的时候，添加用户
      users.push({ username, password });
      ls("users", users);
      console.log(ls("users"), "注册成功后的账号");
      res.json({
        success: true,
        message: "注册成功",
      });
    } else {
      res.json({
        success: false,
        message: "用户名已存在",
      });
    }
  });

  app.post("/api/login", (req, res) => {
    console.log(req);
    const { username, password } = req.body;
    const users = ls("users");
    if (!users) {
      res.json({
        code: 1,
        message: "账号不存在",
      });
    } else {
      if (!users.find((v) => v.username == username)) {
        res.json({
          code: 1,
          message: "账号不存在",
        });
      } else if (users.find((v) => v.username == username && v.password == password)) {
        res.json({
          code: 0,
          message: "登陆成功",
          username,
          token: "sunclass" + "-" + username + "-" + (new Date().getTime() + 60 * 60 * 1000), //token过期时间1个小时
        });
      } else if (users.find((v) => v.username == username && v.password !== password)) {
        res.json({
          code: 2,
          message: "账号密码错误",
        });
      }
    }
  });

  app.get("/api/user", (req, res) => {
    res.json({
      code: 200,
      message: "获取用户成功",
      username: ls("username"),
      user: ls("user"),
    });
  });
}

export default mock;
